package org.hydrakyoufeng.stuplatform.utils;

import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.util.Base64;

@Component
public class DesUtils {

    /**
     * DES偏移变量，固定占8位字节
     */
    private final static String IV_PARAMETER = "12345678";

    /**
     * DES加密/解密算法-工作模式-填充模式
     */
    private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";

    /**
     * 生成密钥
     * @param key
     * @return
     * @throws Exception
     */
    private Key generateKey(byte[] key) throws Exception {
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        Key sercretKey =  keyFactory.generateSecret(dks);
        return sercretKey;
    }

    /**
     * 使用密钥进行DES加密
     * @param str
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] encode(String str,String key) throws Exception {
        return encode(str.getBytes("UTF-8"),key.getBytes("UTF-8"));
    }

    /**
     * 使用密钥进行DES加密
     * @param value
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] encode(byte[] value,byte[] key) throws Exception {
        Key secretKey = generateKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey,iv);
        return cipher.doFinal(value);
    }

    /**
     * 将明文字符串进行DES加密，再转为Base64字符串
     * @return 加密后的Base64字符串
     */
    public String encodeDESAsBase64(String str,String key) throws Exception {
        byte[] bytes = encode(str,key);
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 将DES加密后的Base64字符串进行解密
     * @return 解密后的字符串
     */
    public String decodeDESAsBase64(String str, String key) throws Exception {
        byte[] bytes = Base64.getDecoder().decode(str.getBytes("UTF-8"));
        Key secretKey = generateKey(key.getBytes("UTF-8"));
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, secretKey,iv);
        bytes = cipher.doFinal(bytes);
        return new String(bytes,"UTF-8");
    }

}
